package com.ubxtech.core.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 *
 * @author Victor.Xiao
 * @since 2022-03-03 20:54
*/
public class Md5Util {

    public static String md5(String val) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(val.getBytes());
            byte[] b = md.digest();
            StringBuffer buf = new StringBuffer("");

            for(int offset = 0; offset < b.length; ++offset) {
                int i = b[offset];
                if (i < 0) {
                    i += 256;
                }

                if (i < 16) {
                    buf.append("0");
                }

                buf.append(Integer.toHexString(i));
            }

            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 经测试感觉比 hashFnv1 分布还均匀点,效率上也没差太多
     * @author Victor.Xiao
     * @since 2023-12-09 17:51
     * @param val val
     * @return int
    */
    public static int hash(String val) {
        return Math.abs(Md5Util.md5(val).hashCode());
    }

    //使用FNV1_32_HASH算法计算服务器的Hash值,这里不使用重写hashCode的方法，最终效果没区别
    public static int hashFnv1(String str){
        final int p = 16777619;
        int hash = (int)2166136261L;
        for (int i = 0; i < str.length(); i++) {
            hash = (hash ^ str.charAt(i)) * p;
        }
        hash += hash << 13;
        hash ^= hash >> 7;
        hash += hash << 3;
        hash ^= hash >> 17;
        hash += hash << 5;

        // 如果算出来的值为负数则取其绝对值
        if (hash < 0) {
            hash = Math.abs(hash);
        }
        return hash;
    }

    public static void main(String[] args) {
        System.out.println(Md5Util.md5("89e89c17f877ca2821b557f633cec3253b0aa9415vlDcMvuwrfTpFsgZIEU"));
    }
}
